import { EndTreatmentReason } from '@CONSTANTS/BleConstants'
import LastTreatmentData from '@MODEL/LastTreatmentData'

const LAST_TREATMENT_TOKENS_SIZE = 18
class LastTreatmentParser {
  private static parseTokens = (tokens: Array<string>): LastTreatmentData => {
    const endReasonTreatment = parseInt(tokens[0], 10) as EndTreatmentReason
    const numberOfPauses = parseInt(tokens[1], 10)
    const enterNoLoadCounter = parseInt(tokens[2], 10)
    const exitNoLoadCounter = parseInt(tokens[3], 10)
    const treatmentDuration = parseInt(tokens[4], 10)
    const pause1duration = parseInt(tokens[5], 10)
    const pause2duration = parseInt(tokens[6], 10)
    const pause3duration = parseInt(tokens[7], 10)
    const errorCode = parseInt(tokens[8], 16)
    const errorCodeParam = parseInt(tokens[9], 10)
    const averageIntensity = parseInt(tokens[10], 10)
    const maxIntensity = parseInt(tokens[11], 10)
    const lastIntensity = parseInt(tokens[12], 10)
    const batteryVoltage = parseInt(tokens[13], 10)
    const lastDeviceOutputVoltage = parseInt(tokens[14], 10)
    const lastDeviceOutputCurrent = parseInt(tokens[15], 10)
    const treatmentTimeLeft = parseInt(tokens[16], 10)
    const timeStamp = parseInt(tokens[17] || '0', 10)
    return new LastTreatmentData({
      endReasonTreatment,
      numberOfPauses,
      enterNoLoadCounter,
      exitNoLoadCounter,
      treatmentDuration,
      pause1duration,
      pause2duration,
      pause3duration,
      errorCode,
      errorCodeParam,
      averageIntensity,
      maxIntensity,
      lastIntensity,
      batteryVoltage,
      lastDeviceOutputVoltage,
      lastDeviceOutputCurrent,
      treatmentTimeLeft,
      timeStamp,
    })
  }

  static parse(data?: string | null) {
    const trimmedString = data?.substr(0, data?.lastIndexOf(String.fromCharCode(0))).trim()
    const tokens = trimmedString?.split(' ')
    if (!tokens || tokens.length !== LAST_TREATMENT_TOKENS_SIZE) {
      console.log('LastTreatmentParser: Parse last treatments status - wrong number of tokens')
      return new LastTreatmentData()
    }
    const lastTreatment = this.parseTokens(tokens)
    console.log('LastTreatmentParser: Last treatment data', lastTreatment)
    return lastTreatment
  }
}

export default LastTreatmentParser
